import {
	isWX
} from "./api.js";
import QRCode from './qrcode.min.js';
//环境检查

const page = () => {
	if (isWX) {
		return;
	}
	// 插入样式
	const s_name = new Date().getTime();
	let div = document.createElement('div');
	div.classList.add(`page-mask-${s_name}`);
	let qrcode = document.createElement('canvas');
	let title = document.createElement('div');
	title.classList.add(`title`);
	title.innerText = "请用微信扫码查看";
	QRCode.toCanvas(qrcode, location.href);
	div.appendChild(qrcode);
	div.appendChild(title);
	document.body.innerHTML = '';
	document.write(
		`<style type="text/css">
		.page-mask-${s_name} {
			position: fixed;
			background: #fff;
			top:0;
			bottom:0;
			left:0;
			right:0;
			z-index:99999999;
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;
		}
		.page-mask-${s_name} .title{
			font-size:24px;
			color:#0055ff;
			margin-top:20px;
		}
	</style>`
	);
	document.body.appendChild(div);
}
page();


import {
	stringObject,
	debounce
} from "./api.js";
import {
	loading
} from './global.js';
import Http from "@/a/utils/fetch";
const $http = new Http();
//微信登录
const appid = process.env.NODE_ENV === 'development' ? 'wxcb8ae2656305c1e2' : 'wx2584f93b93c840e0';
export const wxlogin = debounce(async e => {
	if (!isWX) return {};
	//如果url存在code
	const {
		code,
		...p
	} = stringObject(location.search);
	if (code) {
		const res = await $http.wxlogin({
			code,
			...p
		}).finally(loading({
			msg: '登录中'
		}));
		res.code = res.code - 0;
		if (res.code === 200) { //成功
			return {
				...p,
				...res
			}
		} else if (res.code === 111005) { //用户未绑定
			const {
				msg,
				...j
			} = res;
			return {
				...j,
				...p,
				...JSON.parse(msg)
			}
		}
		return {};
	} else {
		//回调域名
		const yuming = process.env.NODE_ENV === 'development' ? 'http://gzk122.vaiwan.com' + location.pathname : location.href
			.split('#')[0];
		const url =
			`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${
			encodeURIComponent(yuming)
		}&response_type=code&scope=snsapi_userinfo&state=3&connect_redirect=1#wechat_redirect`;
		console.log(url);
		return Promise.reject();
		// location.replace(url);
	}
	return '';
}, 800, true);
